package org.agent.common;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
	
	private static final String[] hexDigits={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	
	public static String MD5Encode(String string){
		
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			try {
				string=byteArrayToHexString(md5.digest(string.getBytes("UTF-8")));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return string;
	}
	
	/**
	 * 把byte[]对象转成字符串
	 * @param digest
	 * @return
	 */
	private static String byteArrayToHexString(byte[] digest) {
		// TODO Auto-generated method stub
//		byte[]128位字节 转换成16进制32为字符串
		StringBuffer result=new StringBuffer();
		for(int i=0;i<digest.length;i++){
			result.append(byteToHexString(digest[i]));
		}
		return result.toString();
	}
	
	/**
	 * byte字节转16进制字符串
	 * @param b
	 * @return
	 */
	private static String byteToHexString(byte b) {
		// TODO Auto-generated method stub
		int n=b;
		if(n<0){
			n=n+256;
		}
		int d1=n/16;//十位数
		int d2=n%16;//个位数
		return hexDigits[d1]+hexDigits[d2];
	}
}

